﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace SkiTracker.Converter
{
    //interesting approach from http://stackoverflow.com/questions/534575/how-do-i-invert-booleantovisibilityconverter

    /// <summary>
    /// Generic Converter for booleans to any type. 
    /// </summary>
    /// <remarks>For explanation see subclass <see cref="BooleanToVisibilityConverter"/>.</remarks>
    public class GenericBooleanConverter<T> : IValueConverter
    {
        public GenericBooleanConverter(T trueValue, T falseValue)
        {
            True = trueValue;
            False = falseValue;
        }

        /// <summary>
        /// Gets or sets the value that represents <see cref="True"/>.
        /// </summary>
        public T True { get; set; }
        /// <summary>
        /// Gets or sets the value that represents <see cref="False"/>.
        /// </summary>
        public T False { get; set; }

        #region IValueConverter Members

        public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool) // && targetType == typeof (T))
            {
                return ((bool) value) ? True : False;
            }
            return DependencyProperty.UnsetValue;
        }

        public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is T && targetType == typeof (bool))
            {
                if (EqualityComparer<T>.Default.Equals((T)value, True)) return true;
                if (EqualityComparer<T>.Default.Equals((T)value, False)) return false;
                return DependencyProperty.UnsetValue;
            }
            return DependencyProperty.UnsetValue;
        }

        #endregion
    }
}